package com.example.android.commitcontent.ime.database.managers;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.example.android.commitcontent.ime.beans.HanZiWord;
import com.example.android.commitcontent.ime.database.hanzi.HanZiStatisticsDataBaseHelper;

import java.lang.ref.WeakReference;
import java.util.List;

public class HanZiWordDictManager {
    private final Context mContext;
    private CallbackHandler mCallbackHandler = new CallbackHandler(this);
    private OnWordsUpdateSuccessListener mOnWordsUpdateSuccessListener;

    private HanZiWordDictManager(Context context) {
        this.mContext = context;
    }

    public void updateWordsDict(List<HanZiWord> hanZiWords, OnWordsUpdateSuccessListener listener) {
        this.mOnWordsUpdateSuccessListener = listener;
        new Thread(new Runnable() {
            @Override
            public void run() {
                HanZiStatisticsDataBaseHelper dataBaseHelper = HanZiStatisticsDataBaseHelper.intance(mContext);
                for (HanZiWord hanZiWord : hanZiWords) {
                    dataBaseHelper.wordsRepeatCount(hanZiWord, hanZiWord.repeatCount, true);
                }
                mCallbackHandler.sendEmptyMessage(0);
            }
        }).start();
    }

    public synchronized static HanZiWordDictManager instance(Context context) {
        return new HanZiWordDictManager(context);
    }


    static class CallbackHandler extends Handler {
        private WeakReference<HanZiWordDictManager> mWeakReference;

        public CallbackHandler(HanZiWordDictManager manager) {
            mWeakReference = new WeakReference<>(manager);
        }

        @Override
        public void handleMessage(Message msg) {
            if (mWeakReference.get() == null) return;
            mWeakReference.get().onWordsUpdated();
//            switch (msg.what) {
//                case 0:
//            }
        }
    }

    private void onWordsUpdated() {
        mOnWordsUpdateSuccessListener.onWordsUpdateSuccess();
    }

    public interface OnWordsUpdateSuccessListener {
        void onWordsUpdateSuccess();
    }
}
